/*
 * XMLEntity.java
 *
 * Created on July 17, 2007, 2:14 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.app.client;

import org.infoset.xml.Document;

/**
 *
 * @author alex
 */
public class XMLEntity
{

   protected Document doc;
   /** Creates a new instance of XMLEntity */
   protected XMLEntity(Document doc)
   {
      this.doc = doc;
   }
   
   public Document getDocument() {
      return doc;
   }
   
   public static String escape(String value) {
      return escape(value,false);
   }
   public static String escape(String value,boolean inAttribute) {
      StringBuilder result = null;
      int len = value.length();
      int pos = 0;
      for (int i=0; i<len; i++) {
         switch (value.charAt(i)) {
            case '<':
               if (result==null) {
                  result = new StringBuilder();
               }
               result.append(value.substring(pos,i));
               result.append("&lt;");
               pos = i+1;
               break;
            case '&':
               if (result==null) {
                  result = new StringBuilder();
               }
               result.append(value.substring(pos,i));
               result.append("&amp;");
               pos = i+1;
               break;
            case '\'':
               if (result==null) {
                  result = new StringBuilder();
               }
               result.append(value.substring(pos,i));
               result.append("&apos;");
               pos = i+1;
               break;
            case '"':
               if (result==null) {
                  result = new StringBuilder();
               }
               result.append(value.substring(pos,i));
               result.append("&quot;");
               pos = i+1;
         }
      }
      if (pos!=len && result!=null) {
         result.append(value.substring(pos));
      }
      return result==null ? value : result.toString();
   }
   
}
